package deviceSyc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/** 
* @author 作者 :		xueyu 
* @date 创建时间:		2017年10月31日 上午9:31:02
* @version 版本:				 
* @description:		
*/

public class JSONAnalysis implements Job{
	String rootPath = System.getProperty("user.dir").replace("\\", "/");
	
	public JSONAnalysis() {
    }

    public static void main(String[] args) {
    	String url = "http://localhost:8080/sc/channel?_type=ws&_method=searchHGChanelInfo";
        String json = loadJSONData(url);
        DataParse(json,"110");
    }
 

    /**
     * <p>
     * Called by the <code>{@link org.quartz.Scheduler}</code> when a
     * <code>{@link org.quartz.Trigger}</code> fires that is associated with
     * the <code>Job</code>.
     * </p>
     * 
     * @throws JobExecutionException
     *             if there is an exception while executing the job.
     */
    public void execute(JobExecutionContext context)
        throws JobExecutionException {
    	System.out.println("start device sys! - " + new Date());
        // device syc
    	FileUtil fu = new FileUtil();
    	String JSONStr = fu.ReadFile(rootPath + "/res/scUrl.json");
    	List<JSONObject> urlObjList = URLParse(JSONStr);
    	System.out.println("get url----url size = " + urlObjList.size());
//    	for(int i=0;i<urlObjList.size();i++){
//    		JSONObject urlObj = urlObjList.get(i);
//    		String json = loadJSONData(urlObj.getString("url"));
//    		DataParse(json,urlObj.getString("cityCode"));
//    	}
    }

    public static String loadJSONData (String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                                        yc.getInputStream(),"UTF-8"));
            String inputLine = null;
            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return json.toString();
    }
	
    public List<JSONObject> URLParse(String json){
    	JSONArray ja = JSONArray.parseArray(json);
    	List<JSONObject> URLlist = new ArrayList<>();
		int provinceNum = 0;
		for (Iterator iterator = ja.iterator(); iterator.hasNext();) {  
            provinceNum++;
			JSONObject obj=(JSONObject)iterator.next();
			URLlist.add(obj);
		}
		System.out.println("province num = " + provinceNum);
		return URLlist;
    }
    /*
     * 原始数据：[id,通道名，台席号，状态，安装区域(设备分类)，机构号，机构名称，上级机构号，上级机构名称]
     * 调整为json数据：：
     *  "sendSycRequest": 
     *  {
        "deviceId": "监控通道ID",
        "monGunNo": "监控通道台席号",
        "monGunName": "监控通道台席中文名",
        "deptId": "机构号（邮储银行统一的机构号）",
        "status": "设备状态（01：启用，02：停用，03：损坏）",
        "deviceBelong": "设备分类，如现金区，库房，自助服务区等",
        "remark":{
        	"upperDeptId": "上级机构号",
        	"upperDeptName": "上级机构名称",
        	"currentDeptName": "当前机构名称",
        	"deptFlag": "是否有机构号，0-否，1-是"
        }
    *	}
    */
	public static void DataParse(String json,String cityCode){
		JSONArray ja = JSONArray.parseArray(json);
		int num = 0;
		for (Iterator iterator = ja.iterator(); iterator.hasNext();) {  
            num++;
			JSONArray jarr=(JSONArray)iterator.next();
			JSONObject obj = new JSONObject();
			JSONObject subObj = new JSONObject();
			JSONObject remark = new JSONObject();
			subObj.put("deviceId", jarr.getString(0));
			subObj.put("monGunNo", jarr.getString(2)==null?"":jarr.getString(2));
			subObj.put("monGunName", jarr.getString(1)==null?"":jarr.getString(1));
			subObj.put("deptId", jarr.getString(5)==null?"":jarr.getString(5));
			subObj.put("status", jarr.getString(3)==null?"01":jarr.getString(3).equals("2")?"02":(jarr.getString(3).equals("3")?"03":"01"));
			subObj.put("deviceBelong", jarr.getString(4)==null?"非现金区":jarr.getString(4).equals("1")?"现金区":(jarr.getString(4).equals("3")?"自助服务区":"非现金区"));
			remark.put("upperDeptId", jarr.getString(7)==null?"":jarr.getString(7));
			remark.put("upperDeptName", jarr.getString(8)==null?"":jarr.getString(8));
			remark.put("currentDeptName", jarr.getString(6)==null?"":jarr.getString(6));
			remark.put("deptFlag", jarr.getString(5)==null?"0":"1");
			subObj.put("remark", remark);
			obj.put("sendSycRequest", subObj);
//			System.out.println(obj);
			DataSend(obj,cityCode);
		}
		System.out.println("解析了 " + num + "条数据");
	}
	
	public static void DataSend(JSONObject obj,String routingKey){
		try {
			MQProducer mqs = new MQProducer();
			mqs.sendMsg(obj.toJSONString(),routingKey);
			mqs.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
